package com.progroup.kyrsmoney;



import java.io.File;
import java.io.IOException;
import java.util.List;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.progroup.checks.Checks;
import com.progroup.checks.q;
import com.progroup.graphics.GraphicsChart;
import com.progroup.kyrsmoney.database.DBAdapter.DatabaseHelper;
import com.progroup.kyrsmoney.dialog.CustomDialog;
import com.progroup.kyrsmoney.parsing.OldHistoryParser;
import com.progroup.kyrsmoney.preferences.PreferencesActivity;
import com.progroup.kyrsmoney.service.ServiceExample;
import com.progroup.tabAndroid4.CustomFragmentAdapter;
import com.viewpagerindicator.PageIndicator;
import com.viewpagerindicator.TabPageIndicator;

public class KyrsMoneyActivity extends SherlockFragmentActivity  {
    /** Called when the activity is first created. */
	
	public static int THREAD_UPDATE_CHEKED=11, THREAD_UPDATE_INFO=12, THREAD_PARSING=13, THREAD_DATA_KYRS=14, THREAD_ONE_START=15;
	
	Menu menu_1;
	int key = 0;
	 LinearLayout linearlayout;
    ViewPager pager = null;
    TabPageIndicator tabIndicator = null;
    ActionBar actionbar = null;
    CustomDialog dialog = null, dialog_load = null;
    View view = null;
    CustomFragmentAdapter mAdapter;
    ViewPager mPager;
    PageIndicator mIndicator;
    
	@Override
	public void onCreate(Bundle savedInstanceState) {
		 setTheme(R.style.Theme_Sherlock);
		super.onCreate(savedInstanceState);	
		
		setContentView(R.layout.main);
		
		if(Checks.isServiceRunning(KyrsMoneyActivity.this, ServiceExample.class.getName())){
			  stopService(new Intent(KyrsMoneyActivity.this, ServiceExample.class));
		  }
		
		
		actionbar = getSupportActionBar();
		Drawable myIcon = getResources().getDrawable( R.drawable.action_bar_fon);
		actionbar.setBackgroundDrawable(myIcon);
		setSizeDisplay();
		linearlayout = (LinearLayout)findViewById(R.id.LinearLayout1e);
		
		
		// alert();
		if(Checks.DB_THERE(this)){
			PreferencesActivity.addPref(this);
			dialog_load = new CustomDialog(KyrsMoneyActivity.this, Checks.DIALOG_LOADING, null);
			dialog_load.show();
			new ThreadTask().execute(THREAD_DATA_KYRS+"");
		}else{
			PreferencesActivity.setpreference(this);
			if(Checks.isOnline(this)){
				try{
						copyDB();
						dialog_load = new CustomDialog(KyrsMoneyActivity.this, Checks.DIALOG_LOADING, "text");
						dialog_load.show();
						new ThreadTask2().execute();
						
				}catch (Exception e) {
					// TODO: handle exception
				}
			}else{
				KyrsMoneyActivity.this.runOnUiThread(new Runnable() {
					
					public void run() {
						
						alert();
					}
					
				});
			}
		}
				
				
		Checks.ChartMini = Checks.KEYBACK_NO;
	}
	

	

	
	
	
	
	public View Page(){
		Log.i("PAGE!!!!!", "!!!!!!");
		Checks.context= KyrsMoneyActivity.this;
			
			//if(pager!=null){
			//	pager.setAdapter(null);
			//}
			Log.i("PAGE!!!!!", "1");
			mAdapter = new CustomFragmentAdapter(getSupportFragmentManager());
			LayoutInflater inflater = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			view = new View(this);
			view = inflater.inflate(R.layout.main_tab_layout,null);
			tabIndicator = (TabPageIndicator)view.findViewById(R.id.indicator);
			pager = (ViewPager)view.findViewById(R.id.pager);
			pager.setAdapter(mAdapter);
			pager.setDrawingCacheEnabled(true);
			tabIndicator.setViewPager(pager);
			tabIndicator.setDrawingCacheEnabled(true);
			return view;
			
	}	
	
	
	@Override
	protected void onRestart() {
		
		super.onRestart();
		
		Log.e("ONRESTART!!!!!!!!!!", "TRUE");
		if(!Checks.ChartMini){
			linearlayout.removeAllViews();
			linearlayout.addView(Page(), new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
		}
		Checks.ChartMini = Checks.KEYBACK_NO;
	}
	
	
	public void alert(){
		
		AlertDialog alertDialog = new AlertDialog.Builder(KyrsMoneyActivity.this).create();
		alertDialog.setTitle(getText(R.string.dialog_exception_internet));
		alertDialog.setButton("Ок", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) { 
				System.exit(0);
			}
		});
	   
	   alertDialog.show();
	   
   }
    
   
    public void copyDB(){
    	 DatabaseHelper myDbHelper = new DatabaseHelper(KyrsMoneyActivity.this);
  	    
    	 try {
    		 myDbHelper.createDataBase();
    		 Log.d("KyrsMoneyActivity","copy done succesfful");
    		 myDbHelper.close();
    		 
    	 } catch (IOException ioe) {
    		 Log.d("KyrsMoneyActivity","ERROR copiring");}
    	 
    	 
    	 try{ 
    		 File DB_PATH = this.getDatabasePath("DataBase");
    		 if(DB_PATH.exists()){
    			 DB_PATH.delete();
    		 }
    	 }catch (Exception e) {
    		 // TODO: handle exception
    	 }

    }
    
    
    
    
    
    
    
    
    @Override 
    public boolean onCreateOptionsMenu(Menu menu) 
    { 
    	this.menu_1=menu;
    	MenuInflater inflater=getSupportMenuInflater();
    	inflater.inflate(R.menu.menu, menu);
    	 
    	//return true; 
    	return super.onCreateOptionsMenu(menu);
    }
    
    
      
      
      @Override 
      public boolean onOptionsItemSelected(MenuItem item) 
      {
    	  switch (item.getItemId())
    	  {
    	  
    	  case R.id.updateitem1: 
    		  
    		  dialog_load = new CustomDialog(KyrsMoneyActivity.this, Checks.DIALOG_LOADING, null);
    		  dialog_load.show();
    		  new ThreadTask().execute(THREAD_PARSING+"");
    		  break;
    	  case R.id.subitem1:
    		  startActivity(new Intent(KyrsMoneyActivity.this, GraphicsChart.class));
    		  
    		  break; 
    	  case R.id.subitem2: 
    		  startActivity(new Intent(KyrsMoneyActivity.this, PreferencesActivity.class)); 
    		  break; 
    	  case R.id.subitem3: 
    		  
    		  dialog = new CustomDialog(KyrsMoneyActivity.this, Checks.DIALOG_LIST, null);
    		  dialog.show();
    		  dialog.b_ok.setOnClickListener(new OnClickListener() {
    			  
    			  public void onClick(View v) {
    				  // TODO Auto-generated method stub
    				  Checks.KeyBack=Checks.KEYBACK_YES;
    				  
    				  dialog.dismiss();
    				  
    				  dialog_load = new CustomDialog(KyrsMoneyActivity.this, Checks.DIALOG_LOADING, null);
    				  dialog_load.show();
    				  new ThreadTask().execute(THREAD_UPDATE_CHEKED+"");
    			  }
    		  });
    		  dialog.b_cancel.setOnClickListener(new OnClickListener() {
    			  
    			  public void onClick(View v) {
    				  // TODO Auto-generated method stub
    				  Checks.KeyBack=Checks.KEYBACK_YES;
    				  dialog.dismiss();
    				  
    				  dialog_load = new CustomDialog(KyrsMoneyActivity.this, Checks.DIALOG_LOADING, null);
    				  dialog_load.show();
    				  new ThreadTask().execute(THREAD_UPDATE_INFO+"");
    			  }
    		  });
    		  break; 
    	  case R.id.subitem4: 
    		  startService(new Intent(KyrsMoneyActivity.this, ServiceExample.class));
    		  KyrsMoneyActivity.this.finish();
    		  break;
    	  default: 
    		  return false; 
    	  }
    	  return super.onOptionsItemSelected(item); 
      }
      
    
       
      private class ThreadTask extends AsyncTask<String, Void, List<String>> {
    	  
    	  protected List<String> doInBackground(String... params) {
    		
    			try{//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    		
    			  if(Checks.getint(params[0])==THREAD_PARSING){
    				  q.Parsing(KyrsMoneyActivity.this);
    				  q.getBanksKyrs(KyrsMoneyActivity.this);
    			  } else if(Checks.getint(params[0])==THREAD_UPDATE_CHEKED){
    				  q.UpdateCheked(KyrsMoneyActivity.this);
    				  q.getBanksInfo(KyrsMoneyActivity.this);
    				  q.getBanksKyrs(KyrsMoneyActivity.this);
    			  }else if(Checks.getint(params[0])==THREAD_UPDATE_INFO){
    				  q.getBanksInfo(KyrsMoneyActivity.this);
    			  }else if(Checks.getint(params[0])==THREAD_DATA_KYRS){
    				  q.getBanksInfo(KyrsMoneyActivity.this);
    				  q.getBanksKyrs(KyrsMoneyActivity.this);
    			  }else if(Checks.getint(params[0])==THREAD_ONE_START){
    				  q.UpdateCheked(KyrsMoneyActivity.this);
    				  q.Parsing(KyrsMoneyActivity.this);
    				  q.getBanksInfo(KyrsMoneyActivity.this);
    				  q.getBanksKyrs(KyrsMoneyActivity.this);
    			  }
    			}catch (Exception e) {
					// TODO: handle exception
				}
    		  return null;
    	  }
    	  
    	  
    	  protected void onPostExecute(List<String> output) {
    		  
    		 try{
    			linearlayout.removeAllViews();
    			 linearlayout.addView(Page(), new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
    			 
    		 }catch (Exception e) {
				// TODO: handle exception
    			 Log.e("THREAD!!!onPostExecute!!!linearlayout", e.toString());
			}
    		  try{
    			  Checks.KeyBack=Checks.KEYBACK_YES;
    			  if(dialog_load!=null){
    			  dialog_load.dismiss();
    			  }
    		  }catch (Exception e) {
				// TODO: handle exception
    			  Log.e("THREAD!!!onPostExecute!!!DIALOG", e.toString());
			}
    		  
    	  }
    	  
      }
      
private class ThreadTask2 extends AsyncTask<String, Void, List<String>> {
    	  
    	  protected List<String> doInBackground(String... params) {
    		 
      			q.getBanksInfo(KyrsMoneyActivity.this);
      			OldHistoryParser parser = new OldHistoryParser(KyrsMoneyActivity.this);
      			parser.setParsing();
    		  return null;
    	  }
    	  
    	  protected void onPostExecute(List<String> output) {
    		  dialog_load.dismiss();
    		  dialog = new CustomDialog(KyrsMoneyActivity.this, Checks.DIALOG_LIST, null);
        	  dialog.show();
    		  dialog.b_ok.setOnClickListener(new OnClickListener() {
				
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Checks.KeyBack=Checks.KEYBACK_YES;
					dialog.dismiss();
					
					dialog_load = new CustomDialog(KyrsMoneyActivity.this, Checks.DIALOG_LOADING, null);
					dialog_load.show();
  				  new ThreadTask().execute(THREAD_ONE_START+"");
				}
			});
    		  dialog.b_cancel.setOnClickListener(new OnClickListener() {
				
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Checks.KeyBack=Checks.KEYBACK_YES;
					dialog.dismiss();
					
					dialog_load = new CustomDialog(KyrsMoneyActivity.this, Checks.DIALOG_LOADING, null);
					dialog_load.show();
  				  new ThreadTask().execute(THREAD_UPDATE_INFO+""); //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
				}
			});
        	 
    	  }
      }
      
      public void setSizeDisplay(){
  		//Checks.density = (int) getResources().getDisplayMetrics().density;
    	  Checks.dispaly = getResources().getDisplayMetrics();
    	  //float ht_px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, ht, getResources().getDisplayMetrics());
    	  //float wt_px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, wt, getResources().getDisplayMetrics());
      }

      @Override
      public boolean onKeyDown(int keyCode, KeyEvent event) {
    	  // TODO Auto-generated method stub
    	  Log.i("KEYKODE1", keyCode+"");
    	  if(Checks.KeyBack){
    			  return super.onKeyDown(keyCode, event);
    			  
    	  }else{
    		  return false;
    	  }
      }
      
    
      
      @Override
    protected void onDestroy() {
    	// TODO Auto-generated method stub
    	  startService(new Intent(KyrsMoneyActivity.this, ServiceExample.class));
    	super.onDestroy();
    }
      
 }